import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:http/http.dart' as http;

class OnlineActionPage extends StatefulWidget {
  const OnlineActionPage({super.key});

  @override
  State<OnlineActionPage> createState() => _OnlineActionPageState();
}

class _OnlineActionPageState extends State<OnlineActionPage> {
  final FocusNode _focusNode1 = FocusNode();
  final FocusNode _focusNode2 = FocusNode();
  final FocusNode _focusNode3 = FocusNode();
  final FocusNode _focusNode4 = FocusNode();
  final FocusNode _focusNode5 = FocusNode();

  TextEditingController qrcode = TextEditingController(text: "");
  TextEditingController qrcode1 = TextEditingController(text: "");
  TextEditingController qrcode2 = TextEditingController(text: "");
  TextEditingController qrcode3 = TextEditingController(text: "");
  TextEditingController qrcode4 = TextEditingController(text: "");

  Future<bool> onlineService() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      if (qrcode.text == "" &&
          (qrcode1.text == "" ||
              qrcode2.text == "" ||
              qrcode3.text == "" ||
              qrcode4.text == "")) {
        TDToast.showFail("请完成扫码！", context: context);
        return false;
      }
      var res = await http.post(
        Uri.parse(
          "http://${prefs.getString("address")}:${prefs.getString("port")}/api/countLine/generate",
        ),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(<String, dynamic>{
          "BarCode": qrcode.text.trim(),
          "CompressorCode": qrcode1.text.trim(),
          "CompressorCode2": qrcode2.text.trim(),
          "CompressorCode3": qrcode3.text.trim(),
          "CompressorCode4": qrcode4.text.trim(),
          "Line": prefs.getString("line").toString().trim(),
        }),
      );
      final responseJson = json.decode(res.body);
      final code = responseJson["result"];
      if (code) {
        TDToast.showSuccess("上线成功了!", context: context);
        qrcode.text = "";
        qrcode1.text = "";
        qrcode2.text = "";
        qrcode3.text = "";
        qrcode4.text = "";
        FocusScope.of(context)
            .requestFocus(_focusNode1.children.first);
        return true;
      }

      TDToast.showText("产品已上线!查看历史", context: context);
    } catch (e) {
      TDToast.showFail("网络请求失败，请检查上位机是否开机", context: context);
    }
    return false;

  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_focusNode1.children.first);
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        SizedBox(
          height: 100,
          child: Padding(
            padding: EdgeInsets.only(left: 4, right: 4),
            child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                ),
                child: KeyboardListener(
                  focusNode: _focusNode1,
                  onKeyEvent: (e) {
                    if (e.logicalKey == LogicalKeyboardKey.enter &&
                        qrcode.text != "") {
                      FocusScope.of(context)
                          .requestFocus(_focusNode2.children.first);
                    }
                  },
                  child: TDInput(
                    textStyle: TextStyle(
                      fontSize: 40,
                    ),
                    leftLabel: '绑定产品码',
                    controller: qrcode,
                    needClear: true,
                    backgroundColor: Colors.white,
                    inputType: TextInputType.none,
                    hintText: '请扫描需要绑定的产品条码',
                    onChanged: (text) {
                      setState(() {
                        qrcode.text = text;
                      });
                    },
                    onClearTap: () {
                      qrcode.clear();
                      setState(() {});
                    },
                  ),
                )),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 10, right: 10),
          child: Column(
            children: [
              SizedBox(height: 5),
              SizedBox(
                  child: Column(
                children: [
                  KeyboardListener(
                    focusNode: _focusNode2,
                    onKeyEvent: (e) {
                      if (e.logicalKey == LogicalKeyboardKey.enter &&
                          qrcode1.text != "") {
                        FocusScope.of(context)
                            .requestFocus(_focusNode3.children.first);
                      }
                    },
                    child: TDInput(
                      textStyle: TextStyle(fontSize: 25),
                      leftLabel: '压缩机编码1',
                      controller: qrcode1,
                      needClear: true,
                      width: double.infinity,
                      backgroundColor: Colors.white,
                      inputType: TextInputType.none,
                      hintText: '请扫描需要绑定的压缩机编码1',
                      onChanged: (text) {
                        setState(() {
                          qrcode1.text = text;
                        });
                      },
                      onClearTap: () {
                        qrcode1.clear();
                        setState(() {});
                      },
                    ),
                  ),
                  SizedBox(height: 5),
                  KeyboardListener(
                    focusNode: _focusNode3,
                    onKeyEvent: (e) {
                      if (e.logicalKey == LogicalKeyboardKey.enter &&
                          qrcode2.text != "") {
                        FocusScope.of(context)
                            .requestFocus(_focusNode4.children.first);
                      }
                    },
                    child: TDInput(
                      leftLabel: '压缩机编码2',
                      textStyle: TextStyle(fontSize: 25),
                      controller: qrcode2,
                      needClear: true,
                      width: double.infinity,
                      backgroundColor: Colors.white,
                      inputType: TextInputType.none,
                      hintText: '请扫描需要绑定的压缩机编码2',
                      onChanged: (text) {
                        setState(() {
                          qrcode2.text = text;
                        });
                      },
                      onClearTap: () {
                        qrcode2.clear();
                      },
                    ),
                  ),
                ],
              )),
              SizedBox(height: 5),
              SizedBox(
                height: 60,
                child: Row(
                  children: [
                    Expanded(
                        flex: 1,
                        child: KeyboardListener(
                          focusNode: _focusNode4,
                          onKeyEvent: (e) {
                            if (e.logicalKey == LogicalKeyboardKey.enter &&
                                qrcode3.text != "") {
                              FocusScope.of(context)
                                  .requestFocus(_focusNode5.children.first);
                            }
                          },
                          child: TDInput(
                            leftLabel: '压缩机编码3',
                            controller: qrcode3,
                            needClear: true,
                            textStyle: TextStyle(fontSize: 17),
                            width: double.infinity,
                            backgroundColor: Colors.white,
                            inputType: TextInputType.none,
                            hintText: '请扫描需要绑定的压缩机编码3',
                            onChanged: (text) {
                              setState(() {
                                qrcode3.text = text;
                              });
                            },
                            onClearTap: () {
                              qrcode3.clear();
                            },
                          ),
                        )),
                    SizedBox(width: 10),
                    Expanded(
                      flex: 1,
                      child: KeyboardListener(
                        focusNode: _focusNode5,
                        onKeyEvent: (e) {
                          if (e.logicalKey == LogicalKeyboardKey.enter &&
                              qrcode4.text != "") {
                            onlineService();
                          }
                        },child: TDInput(
                        leftLabel: '压缩机编码4',
                        controller: qrcode4,
                        needClear: true,
                        textStyle: TextStyle(fontSize: 17),
                        width: double.infinity,
                        backgroundColor: Colors.white,
                        inputType: TextInputType.none,
                        hintText: '请扫描需要绑定的压缩机编码4',
                        onChanged: (text) {
                          setState(() {
                            qrcode4.text = text;
                          });
                        },
                        onClearTap: () {
                          qrcode4.clear();
                        },
                      ),)
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 30),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TDButton(
              onTap: () async {
                onlineService();
              },
              text: "产品上线",
              width: 230,
              height: 80,
              textStyle: TextStyle(fontSize: 25),
              size: TDButtonSize.large,
              type: TDButtonType.fill,
              shape: TDButtonShape.rectangle,
              theme: TDButtonTheme.primary,
            ),
            SizedBox(width: 100),
            TDButton(
              onTap: () => {
                qrcode.text = "",
                qrcode1.text = "",
                qrcode2.text = "",
                qrcode3.text = "",
                qrcode4.text = "",
                FocusScope.of(context).requestFocus(_focusNode1.children.first),
              },
              text: "清空条码",
              width: 230,
              textStyle: TextStyle(
                fontSize: 30,
              ),
              height: 80,
              size: TDButtonSize.large,
              type: TDButtonType.fill,
              shape: TDButtonShape.rectangle,
              theme: TDButtonTheme.danger,
            ),
          ],
        ),
      ],
    );
  }
}
